package com.ltedu.auth.component;

import com.ltedu.auth.vo.LoginUser;
import com.ltedu.common.domain.SecurityUser;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: MyJwtAccessTokenConverter
 * @auther: Jerry
 * @date: 2020/12/15 10:51
 * @desctiption: JWT内容增强器
 * @version: 1.0
 */
@Component
public class JwtTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 获取到request对象
        HttpServletRequest request = ((ServletRequestAttributes)
                (RequestContextHolder.getRequestAttributes())).getRequest();
        String remoteAddr = request.getRemoteAddr();
        Map<String, Object> info = new HashMap<>();
        //把用户ID设置到JWT中
        info.put("user_id", loginUser.getUserId());
        info.put("client_ip", remoteAddr);
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }

}